import { DesignPattern } from '@/types';

export const creationalPatterns: DesignPattern[] = [
  // 创建型模式 - 单例
  {
    id: 'singleton',
    name: '单例模式',
    category: 'creational',
    difficulty: '简单',
    description: '单例模式确保一个类只有一个实例，并提供一个全局访问点。这是最简单的设计模式之一，但也是最常用的。',
    principles: [
      '确保一个类只有一个实例',
      '提供全局访问点',
      '控制实例化过程',
      '节省系统资源'
    ],
    useCases: [
      '数据库连接池',
      '日志记录器',
      '配置管理器',
      '缓存管理器',
      '线程池'
    ],
    advantages: [
      '保证唯一实例',
      '节省内存资源',
      '提供全局访问点',
      '控制实例化时机'
    ],
    disadvantages: [
      '违反单一职责原则',
      '难以进行单元测试',
      '可能引起内存泄漏',
      '多线程环境下需要特殊处理'
    ],
    code: `// 单例模式示例
class Singleton {
  private static instance: Singleton;
  private constructor() {
    // 私有构造函数，防止外部实例化
  }
  
  public static getInstance(): Singleton {
    if (!Singleton.instance) {
      Singleton.instance = new Singleton();
    }
    return Singleton.instance;
  }
  
  public someBusinessLogic() {
    // 一些业务逻辑
    console.log('执行业务逻辑');
  }
}

// 线程安全的单例模式
class ThreadSafeSingleton {
  private static instance: ThreadSafeSingleton;
  private static readonly lock = {};
  
  private constructor() {}
  
  public static getInstance(): ThreadSafeSingleton {
    if (!ThreadSafeSingleton.instance) {
      // 双重检查锁定
      if (!ThreadSafeSingleton.instance) {
        ThreadSafeSingleton.instance = new ThreadSafeSingleton();
      }
    }
    return ThreadSafeSingleton.instance;
  }
}

// 使用示例
const singleton1 = Singleton.getInstance();
const singleton2 = Singleton.getInstance();

console.log(singleton1 === singleton2); // true
singleton1.someBusinessLogic();`,
    demoCode: `const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // true`,
    realWorldExamples: [
      {
        title: '数据库连接',
        description: '确保应用程序中只有一个数据库连接实例',
        code: `class DatabaseConnection {
  private static instance: DatabaseConnection;
  private connection: any;
  
  private constructor() {
    this.connection = this.createConnection();
  }
  
  public static getInstance(): DatabaseConnection {
    if (!DatabaseConnection.instance) {
      DatabaseConnection.instance = new DatabaseConnection();
    }
    return DatabaseConnection.instance;
  }
  
  private createConnection() {
    // 创建数据库连接
    return { connected: true };
  }
  
  public query(sql: string) {
    return this.connection.query(sql);
  }
}`
      },
      {
        title: '日志记录器',
        description: '全局唯一的日志记录实例',
        code: `class Logger {
  private static instance: Logger;
  
  private constructor() {}
  
  public static getInstance(): Logger {
    if (!Logger.instance) {
      Logger.instance = new Logger();
    }
    return Logger.instance;
  }
  
  public log(message: string) {
    console.log(\`[\${new Date().toISOString()}] \${message}\`);
  }
}`
      }
    ],
    bestPractices: [
      '考虑使用依赖注入替代单例',
      '注意多线程环境下的线程安全',
      '避免在单例中存储可变状态',
      '提供清理资源的方法'
    ],
    icon: 'Box'
  },

  // 创建型模式 - 工厂方法
  {
    id: 'factory',
    name: '工厂方法模式',
    category: 'creational',
    difficulty: '简单',
    description: '工厂方法模式定义了一个创建对象的接口，让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。',
    principles: [
      '定义创建对象的接口',
      '让子类决定实例化哪个类',
      '将对象创建和使用分离',
      '符合开闭原则'
    ],
    useCases: [
      '创建不同类型的对象',
      '数据库驱动选择',
      '日志记录器选择',
      'UI组件创建',
      '解析器选择'
    ],
    advantages: [
      '避免创建者和具体产品的紧耦合',
      '符合单一职责原则',
      '符合开闭原则',
      '提供了一种扩展的方式'
    ],
    disadvantages: [
      '增加了系统的复杂度',
      '需要创建更多的类',
      '客户端代码可能变得复杂'
    ],
    code: `// 工厂方法模式示例
// 产品接口
interface Animal {
  makeSound(): void;
  getType(): string;
}

// 具体产品
class Dog implements Animal {
  makeSound(): void {
    console.log('Woof! Woof!');
  }
  
  getType(): string {
    return 'Dog';
  }
}

class Cat implements Animal {
  makeSound(): void {
    console.log('Meow! Meow!');
  }
  
  getType(): string {
    return 'Cat';
  }
}

class Bird implements Animal {
  makeSound(): void {
    console.log('Tweet! Tweet!');
  }
  
  getType(): string {
    return 'Bird';
  }
}

// 抽象工厂
abstract class AnimalFactory {
  abstract createAnimal(): Animal;
  
  // 模板方法
  public someOperation(): void {
    const animal = this.createAnimal();
    console.log(\`Created a \${animal.getType()}\`);
    animal.makeSound();
  }
}

// 具体工厂
class DogFactory extends AnimalFactory {
  createAnimal(): Animal {
    return new Dog();
  }
}

class CatFactory extends AnimalFactory {
  createAnimal(): Animal {
    return new Cat();
  }
}

class BirdFactory extends AnimalFactory {
  createAnimal(): Animal {
    return new Bird();
  }
}

// 使用示例
function clientCode(factory: AnimalFactory) {
  factory.someOperation();
}

console.log('Testing Dog Factory:');
clientCode(new DogFactory());

console.log('\\nTesting Cat Factory:');
clientCode(new CatFactory());

console.log('\\nTesting Bird Factory:');
clientCode(new BirdFactory());`,
    demoCode: `const dogFactory = new DogFactory();
const dog = dogFactory.createAnimal();
dog.makeSound(); // Woof! Woof!

const catFactory = new CatFactory();
const cat = catFactory.createAnimal();
cat.makeSound(); // Meow! Meow!`,
    realWorldExamples: [
      {
        title: '数据库连接工厂',
        description: '根据配置创建不同类型的数据库连接',
        code: `abstract class DatabaseFactory {
  abstract createConnection(): DatabaseConnection;
}

class MySQLFactory extends DatabaseFactory {
  createConnection(): DatabaseConnection {
    return new MySQLConnection();
  }
}

class PostgreSQLFactory extends DatabaseFactory {
  createConnection(): DatabaseConnection {
    return new PostgreSQLConnection();
  }
}`
      },
      {
        title: '日志记录器工厂',
        description: '创建不同类型的日志记录器',
        code: `abstract class LoggerFactory {
  abstract createLogger(): Logger;
}

class FileLoggerFactory extends LoggerFactory {
  createLogger(): Logger {
    return new FileLogger();
  }
}

class ConsoleLoggerFactory extends LoggerFactory {
  createLogger(): Logger {
    return new ConsoleLogger();
  }
}`
      }
    ],
    bestPractices: [
      '使用工厂方法替代直接实例化',
      '保持工厂方法的简单性',
      '考虑使用参数化工厂方法',
      '结合其他创建型模式使用'
    ],
    icon: 'Factory'
  },

  // 创建型模式 - 抽象工厂
  {
    id: 'abstract-factory',
    name: '抽象工厂模式',
    category: 'creational',
    difficulty: '中等',
    description: '抽象工厂模式提供一个接口，用于创建相关或依赖对象的家族，而不需要明确指定具体类。',
    principles: [
      '提供创建产品家族的接口',
      '确保产品家族的一致性',
      '隔离具体类的生成',
      '易于交换产品系列'
    ],
    useCases: [
      'UI组件库',
      '跨平台应用开发',
      '数据库驱动程序',
      '游戏引擎',
      '主题系统'
    ],
    advantages: [
      '分离接口和实现',
      '产品家族易于交换',
      '有利于产品的一致性',
      '符合开闭原则'
    ],
    disadvantages: [
      '难以支持新种类的产品',
      '增加了系统的抽象性',
      '代码结构复杂'
    ],
    code: `// 抽象工厂模式示例
interface Button {
  render(): void;
}

interface Checkbox {
  render(): void;
}

// 抽象工厂
interface GUIFactory {
  createButton(): Button;
  createCheckbox(): Checkbox;
}

// Windows产品家族
class WindowsButton implements Button {
  render(): void {
    console.log('渲染Windows风格按钮');
  }
}

class WindowsCheckbox implements Checkbox {
  render(): void {
    console.log('渲染Windows风格复选框');
  }
}

// Mac产品家族
class MacButton implements Button {
  render(): void {
    console.log('渲染Mac风格按钮');
  }
}

class MacCheckbox implements Checkbox {
  render(): void {
    console.log('渲染Mac风格复选框');
  }
}

// 具体工厂
class WindowsFactory implements GUIFactory {
  createButton(): Button {
    return new WindowsButton();
  }
  
  createCheckbox(): Checkbox {
    return new WindowsCheckbox();
  }
}

class MacFactory implements GUIFactory {
  createButton(): Button {
    return new MacButton();
  }
  
  createCheckbox(): Checkbox {
    return new MacCheckbox();
  }
}

// 使用示例
function createUI(factory: GUIFactory) {
  const button = factory.createButton();
  const checkbox = factory.createCheckbox();
  
  button.render();
  checkbox.render();
}

// 根据平台选择工厂
const factory = process.platform === 'darwin' 
  ? new MacFactory() 
  : new WindowsFactory();
  
createUI(factory);`,
    demoCode: `const factory = new WindowsFactory();
const button = factory.createButton();
const checkbox = factory.createCheckbox();
button.render();
checkbox.render();`,
    realWorldExamples: [
      {
        title: 'React UI组件库',
        description: '不同主题的组件家族',
        code: `const ThemeFactory = {
  light: () => ({ Button: LightButton, Input: LightInput }),
  dark: () => ({ Button: DarkButton, Input: DarkInput })
};`
      },
      {
        title: '数据库连接',
        description: '不同数据库的连接器家族',
        code: `const DBFactory = {
  mysql: () => ({ connection: MySQLConnection, query: MySQLQuery }),
  postgres: () => ({ connection: PostgresConnection, query: PostgresQuery })
};`
      }
    ],
    bestPractices: [
      '确保产品家族的一致性',
      '使用工厂方法创建产品',
      '避免在客户端代码中直接实例化产品',
      '考虑使用配置来选择具体工厂'
    ],
    icon: 'Factory'
  },

  // 创建型模式 - 建造者
  {
    id: 'builder',
    name: '建造者模式',
    category: 'creational',
    difficulty: '中等',
    description: '建造者模式使你能够分步骤创建复杂对象。该模式允许你使用相同的创建代码生成不同类型和形式的对象。',
    principles: [
      '分步骤创建复杂对象',
      '相同的构建过程可以创建不同的表示',
      '将复杂对象的构建与表示分离',
      '精细控制构建过程'
    ],
    useCases: [
      'SQL查询构建器',
      '配置对象创建',
      'HTTP请求构建',
      '复杂表单构建',
      '游戏角色创建'
    ],
    advantages: [
      '可以分步骤创建对象',
      '生成不同形式的产品',
      '更好的代码复用',
      '符合单一职责原则'
    ],
    disadvantages: [
      '增加代码复杂度',
      '需要创建多个新类',
      '客户端代码可能变得复杂'
    ],
    code: `// 建造者模式示例
class Computer {
  public cpu: string = '';
  public memory: string = '';
  public storage: string = '';
  public gpu: string = '';
  
  public display(): void {
    console.log(\`Computer: \${this.cpu}, \${this.memory}, \${this.storage}, \${this.gpu}\`);
  }
}

// 抽象建造者
interface ComputerBuilder {
  setCPU(cpu: string): ComputerBuilder;
  setMemory(memory: string): ComputerBuilder;
  setStorage(storage: string): ComputerBuilder;
  setGPU(gpu: string): ComputerBuilder;
  build(): Computer;
}

// 具体建造者
class GamingComputerBuilder implements ComputerBuilder {
  private computer: Computer;
  
  constructor() {
    this.computer = new Computer();
  }
  
  setCPU(cpu: string): ComputerBuilder {
    this.computer.cpu = cpu;
    return this;
  }
  
  setMemory(memory: string): ComputerBuilder {
    this.computer.memory = memory;
    return this;
  }
  
  setStorage(storage: string): ComputerBuilder {
    this.computer.storage = storage;
    return this;
  }
  
  setGPU(gpu: string): ComputerBuilder {
    this.computer.gpu = gpu;
    return this;
  }
  
  build(): Computer {
    return this.computer;
  }
}

// 指挥者
class ComputerDirector {
  buildGamingComputer(builder: ComputerBuilder): Computer {
    return builder
      .setCPU('Intel i9-12900K')
      .setMemory('32GB DDR4')
      .setStorage('1TB NVMe SSD')
      .setGPU('RTX 4080')
      .build();
  }
  
  buildOfficeComputer(builder: ComputerBuilder): Computer {
    return builder
      .setCPU('Intel i5-12400')
      .setMemory('16GB DDR4')
      .setStorage('512GB SSD')
      .setGPU('集成显卡')
      .build();
  }
}

// 使用示例
const director = new ComputerDirector();
const builder = new GamingComputerBuilder();

const gamingPC = director.buildGamingComputer(builder);
gamingPC.display();`,
    demoCode: `const builder = new GamingComputerBuilder();
const computer = builder
  .setCPU('Intel i9')
  .setMemory('32GB')
  .setStorage('1TB SSD')
  .setGPU('RTX 4080')
  .build();
computer.display();`,
    realWorldExamples: [
      {
        title: 'SQL查询构建器',
        description: '分步骤构建复杂SQL查询',
        code: `const query = new QueryBuilder()
  .select(['name', 'email'])
  .from('users')
  .where('age > 18')
  .orderBy('name')
  .build();`
      },
      {
        title: 'HTTP请求构建器',
        description: '构建复杂的HTTP请求',
        code: `const request = new RequestBuilder()
  .url('/api/users')
  .method('POST')
  .header('Content-Type', 'application/json')
  .body({ name: 'John' })
  .build();`
      }
    ],
    bestPractices: [
      '使用流畅接口提高可读性',
      '考虑使用指挥者简化构建过程',
      '验证必需参数的设置',
      '支持方法链式调用'
    ],
    icon: 'Layers'
  },

  // 创建型模式 - 原型
  {
    id: 'prototype',
    name: '原型模式',
    category: 'creational',
    difficulty: '简单',
    description: '原型模式允许复制已有对象，而又无需使代码依赖它们所属的类。',
    principles: [
      '通过复制现有实例来创建新对象',
      '避免创建对象时的初始化开销',
      '动态地添加或删除产品',
      '减少子类的构造'
    ],
    useCases: [
      '对象创建成本高昂',
      '避免工厂类层次结构',
      '运行时动态配置',
      '缓存复杂对象',
      '游戏对象克隆'
    ],
    advantages: [
      '性能优于直接创建',
      '简化对象创建',
      '可以克隆复杂对象',
      '运行时动态配置'
    ],
    disadvantages: [
      '克隆复杂对象可能困难',
      '需要实现克隆方法',
      '深拷贝vs浅拷贝问题'
    ],
    code: `// 原型模式示例
interface Cloneable {
  clone(): Cloneable;
}

// 具体原型
class Shape implements Cloneable {
  public x: number = 0;
  public y: number = 0;
  public color: string = '';
  
  constructor(x?: number, y?: number, color?: string) {
    if (x !== undefined) this.x = x;
    if (y !== undefined) this.y = y;
    if (color !== undefined) this.color = color;
  }
  
  clone(): Shape {
    return new Shape(this.x, this.y, this.color);
  }
  
  display(): void {
    console.log(\`Shape at (\${this.x}, \${this.y}) with color \${this.color}\`);
  }
}

class Circle extends Shape {
  public radius: number = 0;
  
  constructor(x?: number, y?: number, color?: string, radius?: number) {
    super(x, y, color);
    if (radius !== undefined) this.radius = radius;
  }
  
  clone(): Circle {
    return new Circle(this.x, this.y, this.color, this.radius);
  }
  
  display(): void {
    console.log(\`Circle at (\${this.x}, \${this.y}) with radius \${this.radius} and color \${this.color}\`);
  }
}

// 原型管理器
class ShapeCache {
  private static cache: Map<string, Shape> = new Map();
  
  static loadCache(): void {
    const circle = new Circle(10, 10, 'red', 5);
    const rectangle = new Shape(20, 20, 'blue');
    
    this.cache.set('circle', circle);
    this.cache.set('rectangle', rectangle);
  }
  
  static getShape(shapeId: string): Shape | undefined {
    const cachedShape = this.cache.get(shapeId);
    return cachedShape ? cachedShape.clone() : undefined;
  }
}

// 使用示例
ShapeCache.loadCache();

const clonedCircle = ShapeCache.getShape('circle');
if (clonedCircle) {
  clonedCircle.display();
}

const clonedRectangle = ShapeCache.getShape('rectangle');
if (clonedRectangle) {
  clonedRectangle.x = 30;
  clonedRectangle.display();
}`,
    demoCode: `const original = new Circle(10, 10, 'red', 5);
const cloned = original.clone();
cloned.x = 20;
cloned.display();`,
    realWorldExamples: [
      {
        title: '游戏对象克隆',
        description: '克隆游戏中的敌人或道具',
        code: `class Enemy {
  clone(): Enemy {
    return Object.assign(Object.create(Object.getPrototypeOf(this)), this);
  }
}`
      },
      {
        title: '配置对象复制',
        description: '复制复杂的配置对象',
        code: `class Config {
  clone(): Config {
    return JSON.parse(JSON.stringify(this));
  }
}`
      }
    ],
    bestPractices: [
      '实现深拷贝避免引用问题',
      '考虑使用原型管理器',
      '注意循环引用问题',
      '性能测试克隆vs创建'
    ],
    icon: 'Shield'
  }
];
